﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ERPStore.Extensions;

using CloudSoft.Extensions;

namespace ERPStore.Exporter.Providers
{
	public class IdealoExport : ExportBase
	{
		private System.Text.StringBuilder m_Document;

		public IdealoExport()
		{

		}

		public override void InitializeSettings(Models.Settings settings)
		{
			settings.FileName = "idealo.txt";
		}

		public override string Name
		{
			get { return "Idealo"; }
		}

		public override string LeadSourceId
		{
			get { return "A781ED49-B701-4C3D-B098-BF47DABB6308"; }
		}

		public override void CreateDocument()
		{
			m_Document = new System.Text.StringBuilder();
			m_Document.AppendLine("Numéro d'article (interne);EAN (European article number);Référence fabricant (HAN);Marque / Fabricant;Produit;Catégorie;Prix en € (TVA incluse);Délai de Livraison;Frais de port;URL produit;URL photo;Ecotaxe (si non incluse dans le prix);Prix Promo (facultatif)");
		}

		public override void AddElementToDocument(ERPStore.Models.Product product, ERPStore.Models.ProductStockInfo productStock)
		{
			var categorie = GetDeepCategoryName(product);
			var identifiant_unique = product.Code;
			var titre = (product.PageTitle ?? product.Title).Replace(";", " ");
			var prix = string.Format("{0:F2}", product.BestPrice.ValueWithTax);
			// var urlBuilder = new ERPStore.Exporter.ProductUrlBuilder();
			var URL_produit = BuildEncryptedProductUrl(LeadSource, product);
			// urlBuilder.GetProductUrl(leadSource, product); // string.Format("http://{0}/produit/{1}/{2}?estid={3}&utm_source={3}&utm_medium=cpc&estcd={4:yyMMdd}", GlobalConfiguration.Configuration.Settings.DefaultUrl, product.EncodedCode(), product.EncodedLink(), Traker, DateTime.Now);
			var URL_image = string.Empty;
			if (product.DefaultImage != null)
			{
				URL_image = string.Format("http://{0}{1}", GlobalConfiguration.Configuration.Settings.DefaultUrl, string.Format(product.DefaultImage.Url, 0, 0));
			}
			var deliveryCountry = GlobalConfiguration.Configuration.Settings.Shipping.DeliveryCountryList.First(i => i.Country == ERPStore.Models.Country.FRA);
			decimal frais_de_port = deliveryCountry.ShippingFeeAmount;
			if (product.Shipping.Strategy == ERPStore.Models.FeeTransportStrategy.FixedPrice)
			{
				frais_de_port = new ERPStore.Models.Price(product.Shipping.FixedPrice, product.DefaultTaxRate).ValueWithTax;
			}
			else if (product.BestPrice.Value >= deliveryCountry.MinimalFreeOfCarriageAmount)
			{
				frais_de_port = 0;
			}
			string availability = null;
			if (productStock != null)
			{
				if (productStock.PhysicalStock > 0)
				{
					availability = "En stock : Expédition en 48/72H ouvrable";
				}
				else if (productStock.ProvisionnedQuantity > 0)
				{
					availability = string.Format("En cours d'appro {0} jour(s)", productStock.ProvisionningDaysCount + productStock.DeliveryDaysCount);
				}
				else
				{
					availability = string.Format("sur commande, compter {0} jour(s)", productStock.ProvisionningDaysCount + productStock.DeliveryDaysCount);
				}
			}
			else
			{
				availability = string.Format("sur commande");
			}
			var D3E = (product.RecyclePrice != null) ? ToCurrency(product.RecyclePrice.ValueWithTax,true) : "";
			var marque = (product.Brand != null) ? product.Brand.Name : "";
			var EAN = product.Gtin.EAN;
			string promotionalPrice = null;
			if (product.StrikedPrice != null)
			{
				promotionalPrice = prix;
				prix = string.Format("{0:F2}", product.StrikedPrice.Value);
			}

			m_Document.AppendFormat("{0};{1};{2};{3};{4};{5};{6};{7};{8:F2};{9};{10};{11};{12}\r\n"
				, product.Code
				, EAN
				, product.ManufacturerPartNumber
				, marque
				, titre
				, categorie
				, prix
				, availability
				, frais_de_port
				, URL_produit
				, URL_image
				, D3E
				, promotionalPrice
				);

		}

		public override void SaveDocument()
		{
			var path = Configuration.ConfigurationSettings.AppSettings["exportPath"];
			var fileName = System.IO.Path.Combine(path, Settings.FileName);

			if (System.IO.File.Exists(fileName))
			{
				System.IO.File.Delete(fileName);
			}

			System.IO.File.WriteAllText(fileName, m_Document.ToString(), System.Text.Encoding.UTF8);
		}

		public override void Dispose()
		{
			m_Document = null;
		}

		protected override string GetDeepCategoryName(ERPStore.Models.Product product)
		{
			var path = new List<string>();
			var c = product.Category;
			while (true)
			{
				if (c != null)
				{
					path.Add(c.Name);
				}
				else
				{
					break;
				}
				c = c.Parent;
			}
			if (path.IsNullOrEmpty())
			{
				return string.Empty;
			}

			path.Reverse();
			return path.JoinString(" > ");
		}

	}
}
